package com.ruoyi.web.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.util.List;
import java.util.Objects;

/**
 * Mysql工具类
 *
 * @since 2022/8/16 10:51
 */
@Component
@AllArgsConstructor
public class MysqlUtil {

    // 手动开启本地事务
    private final DataSourceTransactionManager dataSourceTransactionManager;
    private final TransactionDefinition transactionDefinition;

    public static final ThreadLocal<TransactionStatus> LOCAL_TX = new ThreadLocal<>();

    public static final Page EMPTY_PAGE = new Page();

    /**
     * 开启本地事务
     *
     * @since 2022/9/5 17:07
     */
    public void startLocalTx() {
        if (!Objects.isNull(LOCAL_TX.get())) {
            return;
        }

        TransactionStatus tx = dataSourceTransactionManager.getTransaction(transactionDefinition);
        LOCAL_TX.set(tx);
    }

    /**
     * 提交本地事务
     *
     * @since 2022/9/5 17:07
     */
    public void commitLocalTx() {
        TransactionStatus tx = LOCAL_TX.get();

        if (Objects.isNull(tx)) {
            return;
        }

        dataSourceTransactionManager.commit(tx);
        LOCAL_TX.remove();
    }

    /**
     * 回滚本地事务
     *
     * @since 2022/9/5 17:07
     */
    public void rollbackLocalTx() {
        TransactionStatus tx = LOCAL_TX.get();

        if (Objects.isNull(tx)) {
            return;
        }

        dataSourceTransactionManager.rollback(tx);
        LOCAL_TX.remove();
    }

    /**
     * 转换page对象
     *
     * @param src  源page对象
     * @param list 数据
     * @return {@link Page< E>}
     * @since 2022/9/13 19:14
     */
    public static <T, E> Page<E> transferPage(Page<T> src, List<E> list) {
        Page<E> res = new Page<>();
        res.setPages(src.getPages());
        res.setCurrent(src.getCurrent());
        res.setSize(src.getSize());
        res.setTotal(src.getTotal());
        res.setRecords(list);
        return res;
    }
}
